package org.example.repository;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Slf4j
@Import({TestConfig.class})
public class RepositoryConfig {

    private static final String TODO = "todo";

    @Bean
    public TodoRepository todoRepository(RepositoryManager repositoryManager) {
        return new TodoRepository(repositoryManager.get(TODO));
    }

    @Bean
    TodoInitializer todoInitializer(TodoRepository todoRepository) {
        return new TodoInitializer(todoRepository);
    }

    @Bean
    public TodoTests todoTests(TodoRepository todoRepository) {
        return new TodoTests(todoRepository);
    }

    @Bean
    public RepositoryRunner repositoryRunner(TodoTests todoTests, TestExecutor testExecutor) {
        return new RepositoryRunner(todoTests, testExecutor);
    }

    @Bean
    public RepositoryManager repositoryManager(SchemaManager schemaManager, RepositoryFactory repositoryFactory) {
        return new RepositoryManager(schemaManager, repositoryFactory);
    }

    @Bean
    public SchemaManager schemaManager(SchemaSynchronizer schemaSynchronizer) {
        SchemaManager schemaManager = new SchemaManager(schemaSynchronizer);
        setupSchemas(schemaManager);
        return schemaManager;
    }

    private void setupSchemas(SchemaManager schemaManager) {
        log.info("register schemas");
        schemaManager.put(new Schema(TODO, Todo.class)
                .property(new Property("id", DataTypes.Int).autoIncrement(true).primaryKey(true))
                .property("title", DataTypes.String));

        log.info("sync schemas");
        schemaManager.sync();
    }
}
